<template>
  <div class="form-container">
    <!-- 添加标题 -->
    <div class="header">添加运动场信息</div>
    <!-- 添加带下划线的文字 -->
    <p class="form-description">所有内容都不允许为空，最多可以上传6张图片</p>

    <BeforeCreate/>

    <el-form
        ref="form"
        :model="form"
        :rules="rules"
        class="responsive-form"
        label-position="left"
        label-width="120px"
    >
      <!-- 内容标题 -->
      <el-form-item label="内容标题" prop="contentTitle">
        <el-input v-model="form.contentTitle" placeholder="请输入内容标题"></el-input>
      </el-form-item>
      <el-form-item label="内容分类" prop="contentCategory">
        <el-select v-model="form.contentCategory" placeholder="请选择内容分类">
          <el-option label="南区操场" value="南区操场"></el-option>
          <el-option label="足球场" value="足球场"></el-option>
          <el-option label="南区篮球场" value="南区篮球场"></el-option>
          <el-option label="北区篮球场" value="北区篮球场"></el-option>
          <el-option label="南区体育馆" value="南区体育馆"></el-option>
          <el-option label="北区体育馆" value="北区体育馆"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否额外消费" prop="contentPrice">
        <el-select v-model="form.contentPrice" placeholder="请选择是否需要额外消费">
          <el-option label="是" value="是"></el-option>
          <el-option label="否" value="否"></el-option>
          <el-option label="分情况" value="分情况"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="内容描述" prop="contentDescription">
        <el-input v-model="form.contentDescription" placeholder="请输入内容描述" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="位置指引" prop="contentGuidePosition">
        <el-input v-model="form.contentGuidePosition"
                  placeholder="请输入位置指引（怎么找到你说的这个地方呢？）"></el-input>
      </el-form-item>
      <el-form-item label="内容图片" prop="contentImage">
        <el-upload
            :action=uploadUrl
            :before-upload="beforeUpload"
            :file-list="fileList"
            :limit="6"
            :on-change="handleChange"
            :on-error="handleError"
            :on-exceed="handleExceed"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            accept="image/*"
            list-type="picture-card"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-input v-model="form.code" placeholder="请输入验证码"></el-input>
        <el-button @click="generateCaptcha">{{ captchaText }}</el-button>
      </el-form-item>
      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {ElMessage} from "element-plus";
import axios from "axios";
import {inject, ref} from "vue";
import BeforeCreate from "@/views/NewCreate/BeforeCreate.vue";

export default {
  components: {
    BeforeCreate,
  },
  created() {
    this.generateCaptcha();
  },
  setup() {
    const uploadUrl = inject("uploadUrl");
    return {uploadUrl};
  },
  data() {
    const captchaText = ref('');
    return {
      form: {
        contentTitle: '',
        contentCategory: '',
        contentPrice: '',
        contentDescription: '',
        contentGuidePosition: '',
        contentImage: [],
        code: ''
      },
      fileList: [],
      dialogImageUrl: '', // 预览图片的 URL
      dialogVisible: false, // 控制预览对话框的显示
      captchaText: captchaText.value,
      rules: {
        contentTitle: [
          {required: true, message: "请输入内容标题", trigger: "blur"},
        ],
        contentCategory: [
          {required: true, message: "请选择内容分类", trigger: "change"},
        ],
        contentPrice: [
          {required: true, message: "请选择是否额外消费", trigger: "change"},
        ],
        contentDescription: [
          {required: true, message: "请输入内容描述", trigger: "blur"},
        ],
        contentGuidePosition: [
          {required: true, message: "请输入位置指引", trigger: "blur"},
        ],
        contentImage: [
          {required: true, message: "请上传内容图片", trigger: "change"},
        ],
        code: [
          {required: true, message: "请输入验证码", trigger: "blur"},
          {
            validator: (rule, value, callback) => {
              if (value !== this.captchaText) {
                callback(new Error("验证码输入错误"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      }
    };
  },
  methods: {
    // 图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 移除图片
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt8M = file.size / 1024 / 1024 < 8; // 文件大小限制为 8MB
      if (!isImage) {
        this.$message.error('只能上传图片格式的文件!');
        return false; // 阻止上传
      }
      if (!isLt8M) {
        this.$message.error('上传的图片大小不能超过 8MB!');
        return false; // 阻止上传
      }
      return true; // 允许上传
    },
    // 上传成功回调
    handleSuccess(response, file, fileList) {
      this.$message.success('上传成功');
      // 假设上传成功后，后端返回图片的 URL
      this.form.contentImage.push(response.data); // 设置图片 URL 到 form 中
      console.log(this.form.contentImage);
      this.fileList = fileList; // 更新 fileList 状态
      console.log('上传成功', response);
    },
    // 上传失败回调
    handleError(err, file, fileList) {
      this.$message.error('上传失败');
      console.error('上传失败', err);
    },
    // 超出上传限制时的回调
    handleExceed(files, fileList) {
      this.$message.warning('最多只能上传 6 张图片');
    },
    generateCaptcha() {
      const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
      let captcha = "";
      for (let i = 0; i < 6; i++) {
        captcha += characters.charAt(Math.floor(Math.random() * characters.length));
      }
      this.captchaText = captcha;
    },
    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          axios.post('/playground/add', {
            contentTitle: this.form.contentTitle,
            contentCategory: this.form.contentCategory,
            contentPrice: this.form.contentPrice,
            contentDescription: this.form.contentDescription,
            contentGuidePosition: this.form.contentGuidePosition,
            contentImage: JSON.stringify(this.form.contentImage),
          })
              .then(response => {
                console.log(response.data);
                ElMessage.success('添加成功');
                this.$router.push('/user/home');
              })
              .catch(error => {
                console.error(error);
                ElMessage.error('添加失败');
              });
        } else {
          ElMessage.error('表单信息填写不完整或有误，请检查！');
          return false;
        }
      });
    },
  }
}
</script>

<style scoped>
.form-container {
  margin: 20px 0; /* 调整外边距，使其向左对齐 */
  padding: 20px;
}

/* 添加标题样式 */
.header {
  background: none;
  padding-top: 5px;
  text-align: left;
  font-size: 20px;
  line-height: 30px;
  font-weight: bold;
}

/* 添加带下划线的文字样式 */
.form-description {
  border-bottom: 1px solid #ddd;
  padding-bottom: 5px;
  color: #666;
  text-align: left;
  line-height: 25px; /* 设置行高 */
}

.responsive-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 强制设置 placeholder 字体为 Zpix */
.form-container ::placeholder {
  font-family: "Zpix", sans-serif !important;
}

/* 强制设置输入框内容的字体为 Zpix */
.form-container input {
  font-family: "Zpix", sans-serif !important;
}
</style>